<template>
    <view class="order-detail-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <text class="nav-title">订单详情</text>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading-state" v-if="isLoading">
            <view class="loading-spinner"></view>
            <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 订单内容 -->
        <view class="order-content" v-if="orderDetail && !isLoading">
            <!-- 订单状态卡片 -->
            <view class="status-card">
                <view class="status-header">
                    <text class="status-title">订单状态</text>
                    <text class="status-value" :class="getStatusClass(orderDetail.status)">{{ orderDetail.status }}</text>
                </view>
                
                <view class="status-actions">
                    <text class="action-title">修改状态：</text>
                    <view class="status-buttons">
                        <button 
                            class="status-btn" 
                            :class="{ 'active': orderDetail.status === '待处理' }"
                            @click="updateOrderStatus('待处理')"
                        >待处理</button>
                        <button 
                            class="status-btn" 
                            :class="{ 'active': orderDetail.status === '处理中' }"
                            @click="updateOrderStatus('处理中')"
                        >处理中</button>
                        <button 
                            class="status-btn" 
                            :class="{ 'active': orderDetail.status === '已完成' }"
                            @click="updateOrderStatus('已完成')"
                        >已完成</button>
                        <button 
                            class="status-btn" 
                            :class="{ 'active': orderDetail.status === '已取消' }"
                            @click="updateOrderStatus('已取消')"
                        >已取消</button>
                    </view>
                </view>
            </view>
            
            <!-- 订单基本信息 -->
            <view class="info-card">
                <view class="card-title">基本信息</view>
                
                <view class="info-item">
                    <text class="info-label">订单编号</text>
                    <text class="info-value">{{ orderDetail.id }}</text>
                </view>
                
                <view class="info-item">
                    <text class="info-label">订单标题</text>
                    <text class="info-value">{{ orderDetail.title }}</text>
                </view>
                
                <view class="info-item">
                    <text class="info-label">提交时间</text>
                    <text class="info-value">{{ formatDate(orderDetail.createdTime) }}</text>
                </view>
                
                <view class="info-item">
                    <text class="info-label">编程语言</text>
                    <view class="language-tags">
                        <view class="language-tag" v-for="(lang, index) in languages" :key="index">{{ lang }}</view>
                    </view>
                </view>
                
                <view class="info-item">
                    <text class="info-label">预算范围</text>
                    <text class="info-value">¥{{ orderDetail.lessBudget }} - {{ orderDetail.highBudget }}</text>
                </view>
                
                <view class="info-item">
                    <text class="info-label">期望完成天数</text>
                    <text class="info-value">{{ orderDetail.expectation }}天</text>
                </view>
            </view>
            
            <!-- 用户信息 -->
            <view class="info-card" v-if="orderDetail.user">
                <view class="card-title">用户信息</view>
                
                <view class="info-item">
                    <text class="info-label">用户名</text>
                    <text class="info-value">{{ orderDetail.user.username || '未设置' }}</text>
                </view>
                
                <view class="info-item">
                    <text class="info-label">手机号</text>
                    <text class="info-value">{{ orderDetail.user.phone || '未绑定' }}</text>
                </view>
                
                <view class="info-item">
                    <text class="info-label">微信号</text>
                    <text class="info-value">{{ orderDetail.user.wechatId || '未绑定' }}</text>
                </view>
                
                <view class="info-item">
                    <text class="info-label">邮箱</text>
                    <text class="info-value">{{ orderDetail.user.email || '未设置' }}</text>
                </view>
            </view>
            
            <!-- 需求详情 -->
            <view class="info-card">
                <view class="card-title">需求详情</view>
                
                <view class="content-box">
                    <text class="content-text">{{ orderDetail.content }}</text>
                </view>
            </view>
            
            <!-- 参考图片 -->
            <view class="info-card" v-if="orderDetail.imageList && orderDetail.imageList.length > 0">
                <view class="card-title">参考图片</view>
                
                <view class="image-grid">
                    <view class="image-item" v-for="(image, index) in orderDetail.imageList" :key="index">
                        <image :src="image" mode="aspectFill" class="reference-image" @click="previewImage(index)"></image>
                    </view>
                </view>
            </view>
            
            <!-- 操作按钮 -->
            <view class="action-buttons">
                <button class="action-btn contact-btn" @click="contactUser">联系用户</button>
                <button class="action-btn back-btn" @click="goBack">返回列表</button>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import request from '@/utils/request';

// 响应式数据
const orderId = ref('');
const orderDetail = ref(null);
const isLoading = ref(true);
const isUpdating = ref(false);

// 计算属性：处理编程语言列表
const languages = computed(() => {
    if (!orderDetail.value || !orderDetail.value.language) return [];
    return orderDetail.value.language.split(';');
});

// 初始化页面
const initPage = () => {
    try {
        // 尝试从onLoad中获取参数
        const onLoadOptions = uni.getStorageSync('order_detail_options');
        if (onLoadOptions && onLoadOptions.id) {
            orderId.value = onLoadOptions.id;
            fetchOrderDetail();
            return;
        }
        
        // 获取当前页面路由
        const pages = getCurrentPages();
        if (!pages || pages.length === 0) {
            showError('无法获取页面参数');
            return;
        }
        
        const currentPage = pages[pages.length - 1];
        
        // 尝试多种方式获取页面参数
        if (currentPage.options && currentPage.options.id) {
            orderId.value = currentPage.options.id;
            fetchOrderDetail();
            return;
        }
        
        if (currentPage.$page && currentPage.$page.options && currentPage.$page.options.id) {
            orderId.value = currentPage.$page.options.id;
            fetchOrderDetail();
            return;
        }
        
        // 尝试从URL中解析
        const fullPath = currentPage.$page?.fullPath || currentPage.route;
        if (fullPath && fullPath.includes('?')) {
            const queryString = fullPath.split('?')[1];
            const params = new URLSearchParams(queryString);
            orderId.value = params.get('id') || '';
            
            if (orderId.value) {
                fetchOrderDetail();
                return;
            }
        }
        
        showError('订单ID不存在');
    } catch (error) {
        console.error('初始化页面参数失败:', error);
        showError('初始化页面失败');
    }
};

// 获取订单详情
const fetchOrderDetail = async () => {
    isLoading.value = true;
    
    try {
        const res = await request('/admin/order/detail', {
            method: 'GET',
            data: {
                id: orderId.value
            }
        });
        
        if (res.code === 200 && res.data) {
            orderDetail.value = res.data;
            
            // 确保imageList是数组
            if (!Array.isArray(orderDetail.value.imageList)) {
                orderDetail.value.imageList = [];
            }
        } else {
            uni.showToast({
                title: res.msg || '获取订单详情失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('获取订单详情失败:', error);
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        });
    } finally {
        isLoading.value = false;
    }
};

// 更新订单状态
const updateOrderStatus = async (status) => {
    if (isUpdating.value) return;
    if (orderDetail.value.status === status) return;
    
    uni.showModal({
        title: '确认修改',
        content: `确定要将订单状态修改为"${status}"吗？`,
        success: async (res) => {
            if (res.confirm) {
                isUpdating.value = true;
                
                try {
                    const result = await request('/admin/order/updateStatus', {
                        method: 'POST',
                        data: {
                            id: orderId.value,
                            status: status
                        }
                    });
                    
                    if (result.code === 200) {
                        uni.showToast({
                            title: '状态更新成功',
                            icon: 'success'
                        });
                        
                        // 更新本地数据
                        orderDetail.value.status = status;
                    } else {
                        uni.showToast({
                            title: result.msg || '更新失败',
                            icon: 'none'
                        });
                    }
                } catch (error) {
                    console.error('更新订单状态失败:', error);
                    uni.showToast({
                        title: '网络错误，请稍后重试',
                        icon: 'none'
                    });
                } finally {
                    isUpdating.value = false;
                }
            }
        }
    });
};

// 获取状态样式类
const getStatusClass = (status) => {
    const classMap = {
        '待处理': 'status-pending',
        '处理中': 'status-processing',
        '已完成': 'status-completed',
        '已取消': 'status-canceled'
    };
    return classMap[status] || '';
};

// 预览图片
const previewImage = (index) => {
    if (!orderDetail.value || !orderDetail.value.imageList || orderDetail.value.imageList.length === 0) return;
    
    uni.previewImage({
        current: index,
        urls: orderDetail.value.imageList
    });
};

// 联系用户
const contactUser = () => {
    if (!orderDetail.value || !orderDetail.value.user) return;
    
    const user = orderDetail.value.user;
    const contactInfo = [];
    
    if (user.phone) contactInfo.push(`电话: ${user.phone}`);
    if (user.wechatId) contactInfo.push(`微信: ${user.wechatId}`);
    if (user.email) contactInfo.push(`邮箱: ${user.email}`);
    
    if (contactInfo.length === 0) {
        uni.showToast({
            title: '用户未提供联系方式',
            icon: 'none'
        });
        return;
    }
    
    uni.showModal({
        title: '联系用户',
        content: contactInfo.join('\n'),
        confirmText: '复制',
        success: (res) => {
            if (res.confirm) {
                // 复制第一个联系方式
                const firstContact = contactInfo[0].split(': ')[1];
                uni.setClipboardData({
                    data: firstContact,
                    success: () => {
                        uni.showToast({
                            title: '已复制到剪贴板',
                            icon: 'success'
                        });
                    }
                });
            }
        }
    });
};

// 返回列表
const goBack = () => {
    uni.navigateBack();
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '未知';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 页面加载
onMounted(() => {
    initPage();
});

// 定义onLoad生命周期函数，用于接收页面参数
defineExpose({
    onLoad: (options) => {
        if (options && options.id) {
            // 将参数存储到本地，以便在mounted中使用
            uni.setStorageSync('order_detail_options', options);
            orderId.value = options.id;
        }
    }
});
</script>

<style lang="scss" scoped>
.order-detail-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #18122B 0%, #120C1C 100%);
    padding-bottom: 40rpx;
}

/* 导航栏样式 */
.nav-bar {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #2D1457;
}

.nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #A259FF;
}

/* 加载状态 */
.loading-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 400rpx;
}

.loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid rgba(162, 89, 255, 0.2);
    border-top: 4rpx solid #A259FF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
}

.loading-text {
    font-size: 28rpx;
    color: #B8B8D1;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 订单内容 */
.order-content {
    padding: 20rpx 30rpx;
}

/* 卡片通用样式 */
.status-card,
.info-card {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    border-radius: 16rpx;
    margin-bottom: 30rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 16rpx #7B2FF244;
    border: 1px solid #2D1457;
}

/* 状态卡片 */
.status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
}

.status-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
}

.status-value {
    font-size: 28rpx;
    padding: 8rpx 24rpx;
    border-radius: 30rpx;
}

.status-pending {
    background: rgba(162, 89, 255, 0.2);
    color: #A259FF;
    border: 1px solid #A259FF;
}

.status-processing {
    background: rgba(16, 174, 255, 0.2);
    color: #10AEFF;
    border: 1px solid #10AEFF;
}

.status-completed {
    background: rgba(39, 194, 129, 0.2);
    color: #27C281;
    border: 1px solid #27C281;
}

.status-canceled {
    background: rgba(255, 75, 75, 0.2);
    color: #FF4B4B;
    border: 1px solid #FF4B4B;
}

.status-actions {
    margin-top: 20rpx;
}

.action-title {
    font-size: 28rpx;
    color: #B8B8D1;
    margin-bottom: 20rpx;
    display: block;
}

.status-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.status-btn {
    flex: 1;
    min-width: 150rpx;
    background: rgba(45, 20, 87, 0.3);
    color: #B8B8D1;
    font-size: 26rpx;
    padding: 15rpx 0;
    border-radius: 8rpx;
    border: 1px solid #2D1457;
    text-align: center;
}

.status-btn.active {
    background: rgba(123, 47, 242, 0.3);
    color: #fff;
    border-color: #7B2FF2;
}

/* 信息卡片 */
.card-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #A259FF;
    margin-bottom: 30rpx;
}

.info-item {
    margin-bottom: 24rpx;
}

.info-label {
    font-size: 26rpx;
    color: #B8B8D1;
    margin-bottom: 10rpx;
    display: block;
}

.info-value {
    font-size: 28rpx;
    color: #fff;
}

/* 语言标签 */
.language-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-top: 10rpx;
}

.language-tag {
    background: rgba(123, 47, 242, 0.2);
    color: #A259FF;
    font-size: 24rpx;
    padding: 6rpx 20rpx;
    border-radius: 30rpx;
    border: 1px solid #7B2FF2;
}

/* 内容框 */
.content-box {
    background: rgba(45, 20, 87, 0.2);
    border: 1px solid #2D1457;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-top: 10rpx;
}

.content-text {
    font-size: 28rpx;
    color: #fff;
    line-height: 1.6;
    white-space: pre-wrap;
}

/* 图片网格 */
.image-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    margin-top: 20rpx;
}

.image-item {
    aspect-ratio: 1/1;
    border-radius: 12rpx;
    overflow: hidden;
    border: 1px solid #2D1457;
}

.reference-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 30rpx;
    margin-top: 40rpx;
}

.action-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
}

.contact-btn {
    background: linear-gradient(45deg, #7B2FF2, #10AEFF);
    color: #fff;
}

.back-btn {
    background: rgba(45, 20, 87, 0.3);
    border: 1px solid #7B2FF2;
    color: #A259FF;
}
</style>